﻿<%@ WebHandler Language="C#" Class="LoginHandler" %>

using System;
using System.Web;
using System.Linq;
using System.Xml.Linq;
using System.Security.Cryptography;
using System.Text;

public class LoginHandler : IHttpHandler, System.Web.SessionState.IRequiresSessionState
{

    private XDocument _usersXML;
    public XDocument UsersXML
    {
        get
        {
            if (this._usersXML == null)
                this._usersXML = XDocument.Load(HttpContext.Current.Server.MapPath("~/App_Data/xmldata/users.xml"));
            return this._usersXML;
        }
    }
    
    public void ProcessRequest (HttpContext context) {
        context.Response.ContentType = "text/plain";
        string username = context.Request.Form["name"].ToString();
        string password = context.Request.Form["pwd"].ToString();
        var users = from user in this.UsersXML.Descendants("User")
                         select new
                         {
                             UserName = user.Element("Name").Value,
                             Password = user.Element("Password").Value
                         };
        MD5 md5 = new MD5CryptoServiceProvider();
        byte[] hashData = md5.ComputeHash(System.Text.Encoding.Default.GetBytes(password));
        StringBuilder returnValue = new StringBuilder();
        for (int i = 0; i < hashData.Length; i++)
        {
            returnValue.Append(hashData[i].ToString());
        }

        System.Collections.Generic.List<SeDuce.Model.User> userList = (from u in users
                where u.Password == returnValue.ToString()
                select new SeDuce.Model.User
                {
                    Username = u.UserName,
                    Password = u.Password
                }).ToList<SeDuce.Model.User>();
        if (userList.Count>0)
        {
            var result = userList[0];
            System.Collections.Generic.List<string> roles;
            switch (result.Username)
            {
                case "Admin":
                    roles = new System.Collections.Generic.List<string>() { "0","1","2" };
                    break;
                case "NewsAdmin":
                    roles = new System.Collections.Generic.List<string>() { "1" };
                    break;
                case "ProductAdmin":
                    roles = new System.Collections.Generic.List<string>() { "2" };
                    break;
                default:
                    roles = new System.Collections.Generic.List<string>();
                    break;
            }
            SessionUser sessionUser = new SessionUser(result.Username, result.Username, roles, string.Empty);
            HttpContext.Current.Session[Utils.SESSIONUSER] = sessionUser;
            
            //save cookie
            HttpCookie cookie = HttpContext.Current.Request.Cookies["SeduceCookies"];
            if (cookie != null)
            {
                HttpCookie myCookie = new HttpCookie("SeduceCookies");
                myCookie.Expires = DateTime.Now.AddDays(-1d);
                HttpCookie encodedCookie = AdamTibi.Web.Security.HttpSecureCookie.Encode(myCookie);
                HttpContext.Current.Response.Cookies.Add(encodedCookie);
            }

            HttpCookie cookie2 = new HttpCookie("SeduceCookies");
            DateTime dtNow = DateTime.Now;
            TimeSpan tsMinute = new TimeSpan(10950, 0, 0, 0);
            cookie2.Expires = dtNow + tsMinute;
            cookie2["SeduceCookies"] = sessionUser.ToJSON().ToString().ToLower();
            HttpCookie encodedCookie2 = AdamTibi.Web.Security.HttpSecureCookie.Encode(cookie2);
            HttpContext.Current.Response.Cookies.Add(encodedCookie2);
            
            context.Response.Write(new { errcode = 0 }.ToJSON());//errcode: 0=成功; 1=失败
            context.Response.End();
        }
        else
        {
            context.Response.Write(new { errcode = 1 }.ToJSON());
            context.Response.End();
        }
    }
 
    public bool IsReusable {
        get {
            return false;
        }
    }

}